<template>
  <div>
    <TopFilter
      ref="topFilter"
      :list="topFilterList"
      :cols="4"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>

    <FilterTable
      ref="table"
      :isSelectColumn="true"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onRowSelectChange="selectChange"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <!-- <el-button :disabled="isChoice" size="small" type="primary" icon="el-icon-plus" @click="release">发布</el-button> -->
        <multiuse-button :disabled="isChoice" size="small" type="primary" icon="el-icon-plus" :click="release" :auth-list="auths" auth-mark="/api/cyxdms.customercare/customercare/carePlan/releaseAutoCarePlan">发布</multiuse-button>
        <!-- <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle">新增</el-button> -->
        <multiuse-button size="small" type="primary" icon="el-icon-plus" :click="addHandle" :auth-list="auths" auth-mark="/api/cyxdms.customercare/customercare/carePlan/insertAutoCarePlan">新增</multiuse-button>
      </template>
    </FilterTable>

    <Drawer
      :visible.sync="visible"
      :title="dialogTitle"
      :width="1100"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <CareTaskPanel :type="handleType" :recordVersion="recordVersion" :carePlanId="carePlanId" @changeHandle="changeHandle" @close="closeHandler" />
    </Drawer>
  </div>
</template>
<script>
import {
  getCareTaskList,
  deleteCareTaskList,
  releaseCareTask,
  disabledAutoCarePlan
} from '@/api/customerCare/visitRules/careTask';
import {
  getUserInfoByRole,
  getUserInfo
} from '@/api/customerCare/saleVisit/careTaskSearch';
import { getConfigHeaders } from '@/api/fetch';
import { dictionary } from '@/utils/dictMixin';
import CareTaskPanel from './careTaskPanel';

import { authority } from '@/utils/authMixin';
export default {
  name: 'CareTask',
  mixins: [dictionary,authority],
  components: {
    CareTaskPanel
  },
  data(){
    this.conf = { add: '新增', edit: '编辑',show: '明细'};
    return {
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchApi: getCareTaskList,
      fetchParams: {},
      recordVersion: '',
      handleType: '',
      carePlanId: '',
      isChoice: true,
      selectedRows: [],
      dialogTitle: '',
      visible: false
    }
  },
  methods: {
    createTopFilters(){
      return [
        {
          type: 'SELECT',
          label: '关爱类型',
          fieldName: 'careTypeCode',
          placeholder: '请选择...',
          itemList: this.createDictList('1572')
        },
        {
          type: 'INPUT',
          label: '关爱名称',
          fieldName: 'careName',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '分配人员',
          fieldName: 'distributeId',
          placeholder: '请输入...',
          itemList: this.createdEmpList()
        },
        {
          type: 'SELECT',
          label: '是否启用',
          fieldName: 'whetherEnable',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        {
          type: 'RANGE_DATE',
          label: '创建日期',
          fieldName: 'createdAtStart|createdAtEnd',
          format: "yyyy-MM-dd",
          placeholder: '创建日期'
        }
      ]
    },
    createTableColumns(){
      return [
       {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          width: 180,
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" divider="after" type="text" disabled={props.row.releaseTag == 10651002} onClick={() => this.editHandle(props.row)} auth-list={this.auths} auth-mark={'/api/cyxdms.customercare/customercare/carePlan/updateAutoCarePlan'}>
                  编辑
                </multiuse-button>
                <multiuse-button size="mini" divider="after" type="text" disabled={props.row.releaseTag == 10651002} onClick={() => this.deleteHandle(props.row)} auth-list={this.auths} auth-mark={'/api/cyxdms.customercare/customercare/carePlan/deleteAutoCarePlan'}>
                  删除
                </multiuse-button>
                <el-button size="mini" type="text" disabled={this.showStop(props.row)} onClick={() => this.stopHandle(props.row)}>
                  停用
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '计划编号',
          dataIndex: 'planNo',
          width: 125,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '关爱类型',
          dataIndex: 'careTypeCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.careTypeCode, '1572')}</div>;
          }
        },
        {
          title: '关爱名称',
          dataIndex: 'careName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '模板类型',
          dataIndex: 'careWay',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.careWay, '1587')}</div>;
          }
        },
        {
          title: '创建日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '基准日期',
          dataIndex: 'baseDateCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.baseDateCode, '1590')}</div>;
          }
        },
        {
          title: '距基准天数',
          dataIndex: 'baseDateDays',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '基准前后',
          dataIndex: 'baselineCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.baselineCode, '1589')}</div>;
          }
        },
        {
          title: '模板名称',
          dataIndex: 'templateName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '分配方式',
          dataIndex: 'distributeWay',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.distributeWay, '1586')}</div>;
          }
        },
        {
          title: '分配人员',
          dataIndex: 'distributeUserName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '是否启用',
          dataIndex: 'whetherEnable',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.whetherEnable, '1004')}</div>;
          }
        },
        {
          title: '执行周期',
          dataIndex: 'executeCycle',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.executeCycle, '1588')}</div>;
          }
        },
        {
          title: '发布状态',
          dataIndex: 'releaseTag',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.releaseTag, '1065')}</div>;
          }
        }
      ]
    },
    release(){
      let param = [];
      this.selectedRows.map(obj=>{
        let data = {carePlanId:obj.carePlanId,recordVersion:obj.recordVersion};
        param.push(data);
      });
      releaseCareTask(param).then(res => {
        if(res.resultCode == 200){
          this.$message.success('发布成功!');
          this.fetchParams = { ...this.fetchParams };
        }else{
          this.$message.error('发布失败!');
          return;
        }
      })
    },
    createdEmpList(){
      //初始化关爱人员选择列表
      getUserInfo().then(res => {
        if(res.resultCode == 200){
          let param = {
            companyId:res.data.userInfo.companyId,
            positionCode:"10061010"
          };
          getUserInfoByRole(param).then(res => {
            if(res.resultCode == 200){
              this.topFilterList[2].itemList = res.data.map(x => ({ value: x.userId, text: x.employeeName }))
            }else{
              this.$message.error('获取关爱人员列表失败!');
            }
          })
        }else{
          this.$message.error('获取当前登录用户信息失败!');
        }
      })
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    selectChange(rows){ //选中时触发的函数
      var flag = false;
      rows.forEach(row=>{
        if(row.releaseTag == 10651002){
          flag = true;
        }
      });
      if(rows.length<=0){
        flag = true;
      }
      this.selectedRows = rows;
      this.isChoice = flag;
    },
    showStop(row){
      if(row.whetherEnable == 10041001 && row.releaseTag == 10651002){
        return false;
      }else{
        return true;
      }
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}关爱计划`;
      this.visible = true;
    },
    editHandle(row){
      this.handleType = 'edit';
      this.recordVersion = row.recordVersion+'';
      this.carePlanId = row.carePlanId+'';
      this.showHandler();
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    changeHandle(val) {
      if(val.createdAtStart&&val.createdAtStart!=''){
        val.createdAtStart = val.createdAtStart.substring(0,10);
      }
      if(val.createdAtEnd&&val.createdAtEnd!=''){
        val.createdAtEnd = val.createdAtEnd.substring(0,10);
      }
      this.fetchParams = Object.assign({}, val);
    },
    stopHandle(row){
      this.$confirm('此操作将停用该计划, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        disabledAutoCarePlan(row.carePlanId).then(res => {
          if(res.data.resultCode == 200){
            this.$message({
              type: 'success',
              message: '停用成功!'
            });
            this.fetchParams = { ...this.fetchParams };
          }else{
            this.$message({
              type: 'error',
              message: res.data.errMsg
            });
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    deleteHandle(row){
      this.$confirm('此操作将删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCareTaskList(row.carePlanId).then(res => {
          if(res.data.resultCode == 200){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchParams = { ...this.fetchParams };
          }else{
            this.$message({
              type: 'error',
              message: res.data.errMsg
            });
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    detailHandle(row){
      this.handleType = 'show';
      this.carePlanId = row.carePlanId+'';
      this.showHandler();
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  }
}
</script>

<style lang="less">
</style>
